﻿using System;
using System.Linq;
using System.Windows.Forms;
using PersonalAccoutingProgram.Data;

namespace PersonalAccoutingProgram.View
{
    public partial class EditIncomesForm : Form
    {
        private int incomesID;
        private DateTime date;
        private decimal amount;
        private string origin;

        public EditIncomesForm(int incomesID, DateTime date, decimal amount, string origin)
        {
            InitializeComponent();
            this.date = date;
            dateTimePicker.Text = date.ToString();
            this.origin = origin;
            comboOrigin.Text = origin;
            this.amount = amount;
            InitializeControls(incomesID);
        }

        private void InitializeControls(int incomesID)
        {
            dateTimePicker.Format = DateTimePickerFormat.Custom;
            dateTimePicker.CustomFormat = DateFormat.DATE_TIME_FORMAT;         
            tbAmount.Text = this.amount.ToString();
            this.incomesID = incomesID;
            InitializeOrigin();
        }

        private void InitializeOrigin()
        {
            var allOrigins =
                   OriginDataClassesDataContext.GetAllOrigines();
            comboOrigin.Items.AddRange(allOrigins.ToArray());
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (DataValidator.isAmountValid(tbAmount.Text))
                {
                    var originID =
                    OriginDataClassesDataContext.GetAllOriginesID(comboOrigin.Text);

                    decimal amountValue = decimal.Parse(tbAmount.Text);                 
                    int originIntID = originID.First();
                    date = DateTime.Parse(dateTimePicker.Text);
                    IncomeDataClassesDataContext.UpdateIncomes(
                        amountValue, originIntID, incomesID, date);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }       

        private void btnDelete_Click(object sender, EventArgs e)
        {
            IncomeDataClassesDataContext.DeleteIncomes(incomesID);
            this.Close();
        }

        

        private void tbAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            DataValidator.ValidateAmount(e);
        }
    }
}